﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MpeCore;
using MpeCore.Classes;
using System.Threading;
using System.IO;
using System.IO.Pipes;

namespace NewMpeInstaller
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        List<PackageClass>  LocalPackages = new List<PackageClass>();
        List<PackageClass> OnlinePackages = new List<PackageClass>();
        PackageClass selectedPack = new PackageClass();
        bool cancel = false;
        public bool silent = false;
        private int counter = -1;
        private List<string> onlineFiles = new List<string>();
        int runningThreads = 0;
        
        List<string> UniqueTags = new List<string>();
        public MainWindow()
        {
            InitializeComponent();
            //using (NamedPipeClientStream client = new NamedPipeClientStream(".", "MPEITest", PipeDirection.InOut))
            //{
            //    Console.WriteLine("Connecting to server ...");
            //    client.Connect();
            //    Console.WriteLine("Connected.");

            //    using (StreamWriter sw = new StreamWriter(client))
            //    {

            //        sw.WriteLine("В");
            //        sw.Flush();
            //    }
            //    client.Close();
            //}
            MpeCore.MpeInstaller.Init();
            MpeCore.MpeInstaller.InstalledExtensions.IgnoredUpdates = ApplicationSettings.Instance.IgnoredUpdates;
            MpeCore.MpeInstaller.KnownExtensions.IgnoredUpdates = ApplicationSettings.Instance.IgnoredUpdates;
            StableButton.IsChecked = ApplicationSettings.Instance.ShowOnlyStable;
            CompatibleButton.IsChecked = ApplicationSettings.Instance.ShowOnlyCompatible;
            ExtensionActions.Visibility = System.Windows.Visibility.Hidden;
            InfoPanel.Visibility = System.Windows.Visibility.Hidden;
            progressBar.Visibility = System.Windows.Visibility.Hidden;
            DownloadCounter.Visibility = System.Windows.Visibility.Hidden;
            DownloadLog.Visibility = System.Windows.Visibility.Hidden;
            LoadGrid();
           ExtensionBlock.ExtensionSelected += new ExtensionSelectedHandler(ExtensionBlock_ExtensionSelected);
        }

        void LoadGrid()
        {
            
            this.Installed.Children.Clear();
            this.Installed.Children.Capacity = 0;
            this.Installed.RowDefinitions.Clear();
            this.Known.Children.Clear();
            this.Known.Children.Capacity = 0;
            this.Known.RowDefinitions.Clear();

            LocalPackages = MpeCore.MpeInstaller.InstalledExtensions.Items;
            OnlinePackages = MpeCore.MpeInstaller.KnownExtensions.GetUniqueList().Items;
            int Row = 0;
            int Column = 0;
            List<string> AllTags = new List<string>();
            foreach (var p in LocalPackages)
            {
                AllTags.AddRange(p.GeneralInfo.TagList.Tags);
                var e = new ExtensionBlock(p);
                e.SetValue(Grid.RowProperty, Row);
                e.SetValue(Grid.ColumnProperty, Column);
                this.Installed.Children.Add(e);
                Column++;
                if (Column == 2)
                {
                    Column = 0;
                    Row++;
                    RowDefinition rowDef = new RowDefinition();
                    rowDef.Height = new GridLength(100);
                    Installed.RowDefinitions.Add(rowDef);
                }

            }

            Row = 0;
            Column = 0;
            foreach (var k in OnlinePackages)
            {
                //AllTags.AddRange(k.GeneralInfo.TagList.Tags);
                var e = new ExtensionBlock(k);
                e.SetValue(Grid.RowProperty, Row);
                e.SetValue(Grid.ColumnProperty, Column);
                this.Known.Children.Add(e);
                Column++;
                if (Column == 2)
                {
                    Column = 0;
                    Row++;
                    RowDefinition rowDef = new RowDefinition();
                    rowDef.Height = new GridLength(100);
                    Known.RowDefinitions.Add(rowDef);
                }

            }
            UniqueTags = AllTags.Distinct().ToList();
            Tags.ItemsSource = UniqueTags;
        }


        public string SearchText
        {
            get { return "Search"; }
        }


        private void button3_Click(object sender, RoutedEventArgs e)
        {

        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {

        }

        private void ExtensionType_Changed(object sender, SelectionChangedEventArgs e)
        {

            ExtensionActions.Visibility = System.Windows.Visibility.Hidden;
            TabItem item = sender as TabItem; 

            if (item != null)
            {
            }
        }

        protected void ExtensionBlock_ExtensionSelected(object sender, ExtensionSelectedArgs e)
        {
            ExtensionActions.Visibility = System.Windows.Visibility.Visible;
            selectedPack = (sender as ExtensionBlock).Package;
            ExtensionDescrition.Text = selectedPack.GeneralInfo.ExtensionDescription;
            ExtensionBigIcon.Source = (sender as ExtensionBlock).ExtensionIcon.Source;

        }

        private void lst1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void ListBoxItem_Selected(object sender, RoutedEventArgs e)
        {
            ExtensionTypeDialog dlg = new ExtensionTypeDialog();
            dlg.Owner = this;
            dlg.ShowDialog();

            InfoPanel.Visibility = System.Windows.Visibility.Visible;
            progressBar.Visibility = System.Windows.Visibility.Visible;
            DownloadCounter.Visibility = System.Windows.Visibility.Visible;
            DownloadLog.Visibility = System.Windows.Visibility.Visible;
            DownloadInfo((bool)dlg.DialogResult.Value);
        }



        private void Stable_Checked(object sender, RoutedEventArgs e)
        {
            ApplicationSettings.Instance.ShowOnlyStable = (bool)StableButton.IsChecked;
            MpeInstaller.KnownExtensions.Hide(ApplicationSettings.Instance.ShowOnlyStable, ApplicationSettings.Instance.ShowOnlyCompatible);
            LoadGrid();
        }

        private void Compatible_Checked(object sender, RoutedEventArgs e)
        {
            ApplicationSettings.Instance.ShowOnlyCompatible = (bool)CompatibleButton.IsChecked;
            MpeInstaller.KnownExtensions.Hide(ApplicationSettings.Instance.ShowOnlyStable, ApplicationSettings.Instance.ShowOnlyCompatible);
            LoadGrid();
        }
        private void Download_Completed(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            InfoPanel.Visibility = System.Windows.Visibility.Hidden;
            progressBar.Visibility = System.Windows.Visibility.Hidden; 
        }

        private void Tags_MouseUp(object sender, MouseButtonEventArgs e)
        {
            object of = Tags.SelectedItem;
        }


        private void DownloadProgress_Changed(object sender, System.Net.DownloadProgressChangedEventArgs e)
        {
        }

        private void DownloadInfo(bool all)
        {
            onlineFiles = MpeCore.MpeInstaller.InstalledExtensions.GetUpdateUrls(new List<string>());
            if (!all)
            {
                onlineFiles = MpeCore.MpeInstaller.KnownExtensions.GetUpdateUrls(onlineFiles);
                onlineFiles = MpeCore.MpeInstaller.GetInitialUrlIndex(onlineFiles);
            }

            if (onlineFiles.Count < 1)
            {
                if (!silent)
                    MessageBox.Show("No online update was found !");
                //Close();
                return;
            }
            progressBar.Maximum = onlineFiles.Count;
            runningThreads = 0;
            for (int i = 1; i <= 5; i++)
            {
                new Thread(DownloadThread).Start();
            }
        }

        void DownloadThread()
        {
            lock (this) { runningThreads++; }
            try
            {
                string tempFile = System.IO.Path.GetTempFileName();
                CompressionWebClient client = new CompressionWebClient();
                int index = -1;
                while (index < onlineFiles.Count && !cancel)
                {
                    lock (this)
                    {
                        counter++;
                        index = counter;
                    }
                    if (index >= onlineFiles.Count)
                        return;
                    string onlineFile = onlineFiles[index];
                    bool success = false;
                    try
                    {
                        client.DownloadFile(onlineFile, tempFile);
                        var extCol = ExtensionCollection.Load(tempFile);
                        lock (this)
                        {
                            MpeCore.MpeInstaller.KnownExtensions.Add(extCol);
                        }
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("Error downloading '{0}': {1}", onlineFile, ex.Message));
                    }
                    Dispatcher.Invoke((Action)(() =>
                    {
                        progressBar.Value++;
                        DownloadCounter.Text = string.Format("[{0}/{1}]", progressBar.Value, progressBar.Maximum);
                        DownloadLog.Text = onlineFile;
                        //listBox1.Items.Add(string.Format("{0}{1}", success ? "+" : "-", onlineFile));
                        //listBox1.SelectedIndex = listBox1.Items.Count - 1;
                        //listBox1.SelectedIndex = -1;
                    }));
                    if (File.Exists(tempFile)) File.Delete(tempFile);
                }
            }
            catch { }
            finally
            {
                lock (this)
                {
                    runningThreads--;
                    if (runningThreads <= 0)
                    {
                        MpeCore.MpeInstaller.Save();
                        Dispatcher.Invoke((Action)(() =>
                        {
                            progressBar.Value = 0;
                            InfoPanel.Visibility = System.Windows.Visibility.Hidden;
                            progressBar.Visibility = System.Windows.Visibility.Hidden;
                            DownloadCounter.Visibility = System.Windows.Visibility.Hidden;
                            DownloadLog.Visibility = System.Windows.Visibility.Hidden;
                            //DialogResult = cancel ? DialogResult.Cancel : DialogResult.OK;
                            //Close();

                        }));
                    }
                }
            }
        }



 
    }
}
